package Concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Callables {
    public static int sum;
    public static final Object locked = new Object();
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //使用callable计算 1 + 2 + 3 + .. + 1000
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                //call() 就相当于 runnable 的run方法 ,一个返回值是void , 一个返回值是泛型参数
                int sum = 0;
                for (int i = 0; i <= 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        //futureTask 表示未来的一个任务
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);
        t.start();
        //get方法就是获取结果 , get会产生阻塞,直到call()执行完成,才会取消阻塞
        Integer result = futureTask.get();
        System.out.println(result);
    }
}
